package com.zhanghe.study.springcloud2.controller;

import com.zhanghe.study.feign.DeptClient;
import com.zhanghe.study.model.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author zh
 * @date 2021/8/19 14:27
 */
@RestController
public class DeptController {
    private static final String REST_URL_PREFIX = "http://localhost:8001";

    // 注意，在使用restTemplate访问微服务时，微服务名称中不能含有_
    private static final String LOAD_REST_URL_PREFIX = "http://MICRO-SERVICE-DEPT-PROVIDER";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    @Qualifier(value="loadRestTemplate")
    private RestTemplate loadRestTemplate;

    @Autowired
    private DeptClient deptClient;

    @RequestMapping(value = "/consumer/dept/add")
    public boolean add(Dept dept) {
        return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);
    }

    @RequestMapping(value = "/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id) {
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class);
    }

    // restTemplate负载均衡调用其他微服务
    @RequestMapping(value = "/consumer/dept/loadget/{id}")
    public Dept loadGet(@PathVariable("id") Long id) {
        return loadRestTemplate.getForObject(LOAD_REST_URL_PREFIX + "/dept/get/" + id, Dept.class);
    }

    // feign调用其他微服务
    @RequestMapping(value = "/consumer/dept/feignget/{id}")
    public Dept feignGet(@PathVariable("id") Long id) {
        return deptClient.get(id);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/consumer/dept/list")
    public List<Dept> list() {
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
    }

    // 测试@EnableDiscoveryClient,消费端可以调用服务发现
    @RequestMapping(value = "/consumer/dept/discovery")
    public Object discovery() {
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/discovery", Object.class);
    }
}
